package controllers;

import jobs.ImageDuplicatesResolver;
import models.automation.events.ImageFixerProgress;
import models.entities.BrandEntity;
import models.entities.DuplicateEntity;
import models.entities.PaginatedProductList;
import models.entities.ProductEntity;
import models.helpers.StringHelper;
import models.repository.ImageRepositorySql;
import models.repository.common.ImageRepository;
import play.Play;
import play.cache.Cache;
import play.mvc.Controller;
import play.mvc.With;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@With(Secure.class)
public class ImageFixer extends Controller {
    private static String webCacheKey = "imagefixerprogress";
    private static ImageRepository imageRepository = new ImageRepositorySql();

    public static void fixImages() {
        String appDataPath = Play.getFile("data").toString();
        ImageDuplicatesResolver duplicatesResolver =
                new ImageDuplicatesResolver(appDataPath, webCacheKey);
        duplicatesResolver.now();
        getStatus();
    }

    public static void readDuplicate(int id) throws IOException {
        imageRepository.readDuplicate(id);
    }

    public static void getDuplicates() throws IOException {
        List<DuplicateEntity> images = imageRepository.getDuplicates();
        for (DuplicateEntity image : images) {
            imageRepository.readDuplicate(image.id);
        }
        if (request.isAjax())
            render("ImageFixer/duplicatesAjax.html", images);
    }

    public static void getProducts(int id) throws IOException {
        List<ProductEntity> products = imageRepository.getProductsByImageId(id);
        PaginatedProductList<ProductEntity> productList = new PaginatedProductList<ProductEntity>(products, 1, 100, 1000, new ArrayList<BrandEntity>());
        render("Product/list.html", productList);
    }

    public static void getStatus() {
        ImageFixerProgress progress;
        if (Cache.get(webCacheKey) != null) {
            progress = (ImageFixerProgress) Cache.get(webCacheKey);
        } else {
            progress = new ImageFixerProgress(0, 0, 0);
        }
        if (progress != null) {
            String percent = StringHelper.getPercentString(progress.md5Processed, progress.totalCount);
            if (request.isAjax()) {
                renderJSON(progress);
            } else {
                render(progress, percent);
            }
        }
    }
}
